package com.gz.steak.modules.system.service.impl;

import com.gz.steak.modules.system.mapper.SysRoleMapper;
import com.gz.steak.modules.system.mapper.SysRoleMenuMapper;
import com.gz.steak.modules.system.pojo.dataobject.SysRole;
import com.gz.steak.modules.system.pojo.dataobject.SysRoleMenu;
import com.gz.steak.modules.system.pojo.model.SysRoleModel;
import com.gz.steak.modules.system.pojo.vo.SysRoleVo;
import com.gz.steak.modules.system.service.SysRoleService;
import com.gz.steak.utils.convert.ConvertUtil;
import com.gz.steak.utils.jwt.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author 刘牌
 * @Date 2020/3/20 0020 21:59
 * @Version 1.0
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {
    private final static Logger logger = LoggerFactory.getLogger(SysRoleServiceImpl.class);
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<SysRoleVo> get() {
        List<SysRole> list = sysRoleMapper.get();
        List<SysRoleVo> sysRoleVos = new ArrayList<>();
        for (SysRole sysRole : list){
            SysRoleVo sysRoleVo = new SysRoleVo();
            sysRoleVo.setId(sysRole.getId())
                    .setRoleRemark(sysRole.getRoleRemark())
                    .setCreateBy(sysRole.getCreateBy())
                    .setCreateTime(ConvertUtil.DateToString(sysRole.getCreateTime()));
            sysRoleVos.add(sysRoleVo);
        }
        return sysRoleVos;
    }

    @Transactional
    @Override
    public void save(SysRoleModel sysRoleModel, HttpServletRequest request) {
        SysRole sysRole = new SysRole();
        sysRole.setCreateTime(ConvertUtil.FormatDate(new Date()))
                .setCreateBy(TokenUtil.getUser(request))
                .setRoleName(sysRoleModel.getRoleName())
                .setRoleRemark(sysRoleModel.getRoleRemark());
        sysRoleMapper.insertSelective(sysRole); //插入角色表
        int id = sysRoleMapper.getIdByRoleName(sysRoleModel.getRoleName());//获取刚插入的角色的id
        logger.info("id  "+id);
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        for (int i = 0 ; i < sysRoleModel.getMenuArray().length ; i++){
            sysRoleMenu.setRoleId((long) id).setMenuId(sysRoleModel.getMenuArray()[i].longValue());
            int s = sysRoleMenuMapper.insertSelective(sysRoleMenu);
            logger.info("s  "+s);
        }
    }
}
